package std

import (
	io_std "clean/adapter/io/http/std"
	"clean/infra/config"
	"clean/infra/io"
	"clean/infra/io/driver"
	"clean/usecase"
	"net"
	"net/http"
	"strconv"
)

type ioDriver struct {
}

func init() {
	io.Register("http_std", &ioDriver{})
}

func (ioDriver) Create(cfg config.Config, app usecase.Input) (io_driver.Io, error) {
	return NewServerStd(cfg, app)
}

// go语言标准库
type ServerStd struct {
	server *http.Server
	port   int
}

func NewServerStd(cfg config.Config, app usecase.Input) (*ServerStd, error) {
	s := &ServerStd{
		port: 8081,
	}
	mux := http.NewServeMux()
	route := io_std.NewHandler(app)
	route.Init(mux)
	s.server = &http.Server{
		Handler: mux,
	}
	return s, nil
}

func (s *ServerStd) Start() error {
	l, err := net.Listen("tcp", ":"+strconv.Itoa(s.port))
	if err != nil {
		return err
	}
	return s.server.Serve(l)
}
